<?php
namespace app\user\controller;
use app\user\model\Wxapp as WxappModel;
use app\user\model\WebEdition as WebEditionModel;
use app\user\model\WebOrder as WebOrderModel;

/**
 * 小程序管理
 */
class Wxapp extends Controller
{
	/**
     * 获取列表
     */
    public function index()
    {
		$model = new WxappModel;
        $list = $model->getList($this->store_user_id);
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
			if(!$list = WebEditionModel::getALL($this->agent_id)){
				$list = WebEditionModel::getALL(0);
			}
            return $this->fetch('add',compact('list'));
        }
        //全局判断
        if($err = checking(1)){
            return $this->renderError($err);
        }
        $model = new WxappModel;
		$wxapp = $this->postData('wxapp');
		$wxapp['store_user_id'] = $this->store_user_id;
		$wxapp['agent_id'] = $this->agent_id;
        if ($model->add($wxapp)) {
            return $this->renderSuccess('创建成功', url('wxapp/index'));
        }
        $error = $model->getError() ?: '创建失败';
        return $this->renderError($error);
    }

    /**
     * 删除
     */
    public function delete($wxapp_id)
    {
		//全局判断
		if($err = checking(1)){
			return $this->renderError($err);
		}
        $model = new WxappModel;
         if ($model->deleteBatch($wxapp_id)) {
			return $this->renderSuccess('删除成功');
        }
		$error = $model->getError() ?: '删除失败';
		return $this->renderError($error);
    }

    /**
     * 登录小程序
     */
    public function login($wxapp_id)
    {
        // 小程序详情
		if($model = WxappModel::getWxapp([
				'wxapp_id' => $wxapp_id,
				'store_user_id' => $this->store_user_id
			])){
			if ($model->login($model)) {
				$this->redirect('/index.php?s=/store/wxapp/setting');
				return false;
			}
		}
		$this->error('登录错误', '/user.php');
		return false;		
    }

    /**
     * 升级续费列表
     */
    public function upgrade($wxapp_id)
    {
		$wxapp = WxappModel::getWxapp(['wxapp_id' => $wxapp_id]);
		if(!$edition = WebEditionModel::getAppType($wxapp['app_type']['value'],$this->agent_id)){
			$edition = WebEditionModel::getAppType($wxapp['app_type']['value'],0);
		}
		if (!$this->request->isAjax()) {
			$this->assign('edition', $edition);
			$this->assign('wxapp', $wxapp);
			return $this->fetch('upgrade');
        }
		$model = new WebOrderModel;
		$data = $this->postData('wxapp');
		$data['store_user_id'] = $this->store_user_id;
		$data['shop_mode'] = $wxapp['shop_mode']['value'];
		$data['web_edition_id'] = $edition['web_edition_id'];
		$data['wxapp_id'] = $wxapp_id;
		$data['agent_id'] = $this->agent_id;
		// 创建订单
		if($model->upgrade($data)) {
			return $this->renderSuccess('续费成功', url('wxapp/index'));
        }
        $error = $model->getError() ?: '续费失败';
        return $this->renderError($error);
    }
}
